import os
import time
import zipfile
from unrar import rarfile

# 判断文件是否为空
def isemptydir(dirpath):
    if len(os.listdir(dirpath)) == 0:
        return True
    else:
        return False

# zip压缩
def makezip(zipdir,zippath):
    # 待压缩的绝对路径
    if os.path.isdir(zipdir) and not isemptydir(zipdir):
        # 遍历所有需要压缩的文件夹
        if os.path.exists(zippath):
            zippath = '%s%s.zip' % (zippath[:-4],int(time.time()))

        zip_file = zipfile.ZipFile(zippath, 'w', zipfile.ZIP_DEFLATED, allowZip64=True)
        file_list = os.listdir(zipdir)
        # 待压缩文件夹内所有文件
        for file_each in file_list:
            # 遍历所有文件夹内的文件
            file_path = os.path.join(zipdir, file_each)
            zip_file.write(file_path, file_each)
        zip_file.close()
    else:
        print(zipdir, "不是文件夹，不进行压缩")

# zip解压
def unzip(zippath,unzippath):
    if zippath.endswith('.zip'):
        zip_file = zipfile.ZipFile(zippath, 'r')  # 压缩文件位置
      
        # 解压的文件夹处理
        if os.path.exists(unzippath) :
            if not isemptydir(unzippath):
                unzippath = '%s%s' % (unzippath, int(time.time()))
                os.mkdir(unzippath)
        else:
            os.mkdir(unzippath)

        # 全部解压，会存在中文乱码问题
        # zip_file.extractall(unzippath)
        # 解决中文乱码问题，将文件先重新编码后再解压
        for infolist in zip_file.infolist():
            infolist.filename = infolist.filename.encode('cp437').decode('gbk')
            zip_file.extract(infolist, unzippath)
        zip_file.close()

        return unzippath
    else:
        print(zippath, "非zip文件，不进行解压！")
 
# rar解压
def unrar(rarpath,unrarpath):
    if rarpath.endswith('.rar'):
        rar_file = rarfile.RarFile(rarpath, 'r')  # 压缩文件位置
      
        # 解压的文件夹处理
        if os.path.exists(unrarpath) :
            if not isemptydir(unrarpath):
                unrarpath = '%s%s' % (unrarpath, int(time.time()))
                os.mkdir(unrarpath)
        else:
            os.mkdir(unrarpath)

        # 全部解压
        rar_file.extractall(unrarpath)

        return unrarpath
    else:
        print(rarpath, "非rar文件，不进行解压！")

# 整合的解压方法
def unCompress(path,unpath):
    file_prefix, file_ext = os.path.splitext(path) 
    if '.zip' == file_ext:
        unzip(path, unpath)
    else:
        unrar(path, unpath)

if __name__ == '__main__': 
    cpath = os.getcwd()
    # zip解压和压缩测试
    # zippath = cpath + "\\test.zip"
    # unzippath = unzip(zippath, cpath+"\\temp")
    # makezip(unzippath, "testPythonZip.zip")   

    # rar解压和压缩测试
    rarpath = cpath + "\\test.rar"
    # unrarpath = unrar(rarpath, cpath+"\\temp")

    unCompress(rarpath, cpath+"\\temp")

